package com.zhuqi.netty.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zhuqi.proto.ChatMessage;
import com.zhuqi.util.WebsocketUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.nio.charset.StandardCharsets;

/**
 * <p>聊天消息返回</p>
 * @author zhuqi
 * @since 2023/3/10 14:21
 */
@Slf4j
public class MessageResponseHandler extends SimpleChannelInboundHandler<ChatMessage.ChatMessageResponse> {


	/**
	 * 聊天消息接收
	 * @param ctx           the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
	 *                      belongs to
	 * @param msg           the message to handle
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ChatMessage.ChatMessageResponse msg) {
		String from = new String(msg.getFrom().getBytes(), StandardCharsets.UTF_8);
		String content = new String(msg.getContent().getBytes(), StandardCharsets.UTF_8);
		String to = new String(msg.getTo().getBytes(), StandardCharsets.UTF_8);
		String message = StrUtil.format("【消息】 {} to {} :{}", from, to, content);
		log.info("message:{}", message);
		// 发送消息到 web
		sendMessage(from, to, content);
	}

	/**
	 * 消息发送
	 * @param from 来源
	 * @param to 发送给
	 * @param content 消息
	 */
	private static void sendMessage(String from, String to, String content) {
		Session ToSession = WebsocketUtil.getUserSession(to);
		if (ObjectUtil.isEmpty(ToSession)) {
			Session fromSession = WebsocketUtil.getUserSession(from);
			if (ObjectUtil.isEmpty(fromSession)) {
				throw new RuntimeException("消息发送人 websocket 会话为空");
			} else {
				WebsocketUtil.sendMessage(fromSession, StrUtil.format("消息发送失败，{} 已从页面下线", to));
			}
		}
		WebsocketUtil.sendMessage(ToSession, StrUtil.format("【消息】 {} :{}", from, content));
	}
}
